<template>
  <div class="patient-list-page">
    <el-card class="patient-list-card">
      <template #header>
        <div class="card-header">
          <span>DICOM文件列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="openUploadDialog">
              导入DCM文件
            </el-button>
            <el-button type="primary" @click="goToUploadTest">
              上传测试
            </el-button>
            <el-button type="primary" @click="fetchPatients" :loading="loading">
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <vxe-table
        :data="patientData"
        :loading="loading"
        class="patient-table"
        border
        stripe
        highlight-hover-row
      >
        <vxe-column type="seq" width="60" title="#"></vxe-column>
        <vxe-column field="fileName" title="文件名" min-width="150"></vxe-column>
        <vxe-column field="patientId" title="患者ID" width="120"></vxe-column>
        <vxe-column field="patientName" title="患者姓名" width="120"></vxe-column>
        <vxe-column field="modality" title="模态" width="100"></vxe-column>
        <vxe-column field="studyDate" title="检查日期" width="120"></vxe-column>
        <vxe-column title="文件数量" width="100" field="fileCount"></vxe-column>
        <vxe-column title="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewImages(row)">
              查看图像
            </el-button>
          </template>
        </vxe-column>
      </vxe-table>
      
      <!-- 空数据提示 -->
      <div v-if="!loading && patientData.length === 0" class="empty-placeholder">
        <el-empty description="暂无患者数据" />
      </div>
    </el-card>
    
    <!-- 文件上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="导入DCM文件"
      width="500px"
      :before-close="handleUploadDialogClose"
    >
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="uploadFileList"
        accept=".dcm"
        multiple
      >
        <el-icon class="el-icon--upload">
          <UploadFilled />
        </el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传DICOM格式文件，支持多文件上传
          </div>
        </template>
      </el-upload>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitUpload" 
            :disabled="uploadFileList.length === 0 || uploading"
            :loading="uploading"
          >
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { VxeTable, VxeColumn } from 'vxe-table'
import { ElCard, ElButton, ElEmpty, ElDialog, ElUpload, ElIcon, ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { api } from '@/utils/api'

const router = useRouter()
const patientData = ref([])
const loading = ref(false)

// 上传对话框相关
const uploadDialogVisible = ref(false)
const uploadFileList = ref([])
const uploading = ref(false)

// 打开上传对话框
const openUploadDialog = () => {
  uploadDialogVisible.value = true
}

// 跳转到上传测试页面
const goToUploadTest = () => {
  router.push('/upload-test')
}

// 处理上传对话框关闭
const handleUploadDialogClose = (done) => {
  if (uploading.value) {
    ElMessage.warning('文件正在上传中，请稍候...')
    return
  }
  done()
}

// 处理文件选择变化
const handleFileChange = (file, files) => {
  uploadFileList.value = files
}

// 处理文件移除
const handleFileRemove = (file, files) => {
  uploadFileList.value = files
}

// 提交上传
const submitUpload = async () => {
  if (uploadFileList.value.length === 0) {
    ElMessage.warning('请先选择要上传的文件')
    return
  }

  uploading.value = true
  try {
    // 逐个上传文件
    for (let i = 0; i < uploadFileList.value.length; i++) {
      const file = uploadFileList.value[i]
      await uploadSingleFile(file)
    }
    
    ElMessage.success('所有文件上传完成')
    uploadDialogVisible.value = false
    uploadFileList.value = []
    
    // 重新获取患者列表
    await fetchPatients()
  } catch (error) {
    ElMessage.error('上传过程中出现错误: ' + error.message)
  } finally {
    uploading.value = false
  }
}

// 上传单个文件
const uploadSingleFile = async (file) => {
  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file.raw)
    
    // 上传文件
    await api.uploadFile(formData)
  } catch (error) {
    throw error
  }
}

// 获取患者列表数据
const fetchPatients = async () => {
  loading.value = true
  try {
    // 使用API工具获取患者数据
    const response = await api.getDicomFiles()
    
    // 处理数据以适配表格
    patientData.value = response.data.map((file, index) => ({
      id: index + 1,
      fileName: file.filename,
      patientId: file.metadata.PatientID || 'N/A',
      patientName: file.metadata.PatientName || 'N/A',
      modality: file.metadata.Modality || 'N/A',
      studyDate: file.metadata.StudyDate || 'N/A',
      fileCount: 1
    }))
  } catch (error) {
    console.error('获取患者数据失败:', error)
    ElMessage.error('获取患者数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 查看图像
const viewImages = (row) => {
  console.log("查看图像:", row.fileName)
  router.push(`/image-viewer/${row.fileName}`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPatients()
})
</script>

<style scoped>
.patient-list-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 60px);
}

.patient-list-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.patient-table {
  margin-top: 20px;
}

.empty-placeholder {
  padding: 40px 0;
  text-align: center;
}

.upload-demo {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>